<template>
  <div>
    <h2>可用优惠券兑换</h2>
    <div class="coupon-list">
      <div v-for="coupon in availableCoupons" :key="coupon.id" class="coupon-item">
        <ElCard class="box-card">
          <template #header>
            <div class="card-header">
              <span>{{ coupon.name }}</span>
            </div>
          </template>
          <div class="card-content">
            <ElTag type="info" v-if="coupon.discount_type === 1">每满减</ElTag>
            <ElTag type="success" v-if="coupon.discount_type === 2">折扣</ElTag>
            <ElTag type="warning" v-if="coupon.discount_type === 3">无门槛</ElTag>
            <ElDivider />
            <p>折扣值：{{ coupon.discount_value }}</p>
            <p>使用门槛：{{ coupon.threshold_amount === 0? '无门槛' : `最低消费金额${coupon.threshold_amount}` }}</p>
            <p>兑换所需积分：{{ coupon.point }}</p>
            <ElButton
                type="primary"
                @click="exchangeCoupon(coupon)"
                :disabled="userPoints.value < coupon.point"
            >
              兑换
            </ElButton>
          </div>
        </ElCard>
      </div>
    </div>
    <div class="user-points">
      <p>您当前的积分：{{ userPoints }}</p>
    </div>
  </div>
</template>

<script setup>
import {ref, onMounted, computed} from 'vue';
import {ElCard, ElButton, ElTag, ElDivider, ElMessageBox} from 'element-plus';
import {getUserById, updateUser} from '@/api/user';
import {getYhCouponsList, updateYhCoupon, addYhUser} from '@/api/coupon';
import axios from 'axios';

// 获取用户ID
const userInfoString = localStorage.getItem('userInfo');
const user = ref(JSON.parse(userInfoString));
const userId = user.value.id;

const coupons = ref([]);
const userPoints = ref(0);

// 获取优惠券列表
const getCoupons = async () => {
  try {
    const response = await getYhCouponsList();
    coupons.value = response.data;
  } catch (error) {
    ElMessageBox.alert('获取优惠券列表出错：' + error.message, '错误', {type: 'error'});
  }
};

// 获取用户积分
const getUserPoints = async () => {
  try {
    const userData = await getUserById(userId);
    userPoints.value = userData.data.points;
    console.log(userPoints)
  } catch (error) {
    ElMessageBox.alert('获取用户积分出错：' + error.message, '错误', {type: 'error'});
  }
};

// 计算可展示给用户的优惠券（仅获取方式为手动领取且领取数未超发放数的）
const availableCoupons = computed(() => {
  return coupons.value.filter(coupon => coupon.obtain_way === 1 && coupon.status === 2 && coupon.used_num < coupon.total_num);
});

// 兑换优惠券的方法（完善了更新用户积分、优惠券used_num和添加用户券信息的逻辑，并使用弹窗显示结果）
const exchangeCoupon = async (coupon) => {
  if (userPoints.value >= coupon.point) {
    try {
      // 更新用户积分
      const updatedUser = {
        ...user.value,
        points: userPoints.value - coupon.point
      };
      console.log(updatedUser)
      await updateUser(updatedUser);

      // 更新优惠券的used_num
      const updatedCoupon = {
        ...coupon,
        used_num: coupon.used_num + 1
      };
      await updateYhCoupon(updatedCoupon);

      // 添加用户券信息
      const yhUser = {
        user_id: userId,
        coupon_id: coupon.id,
        status: 1
      };
      await addYhUser(yhUser);

      ElMessageBox.alert(`成功兑换优惠券：${coupon.name}`, '成功', {type: 'success'});
      // 重新获取用户积分和优惠券列表，以更新页面展示数据
      await getUserPoints();
      await getCoupons();
    } catch (error) {
      ElMessageBox.alert('兑换优惠券时更新数据出错：' + error.message, '错误', {type: 'error'});
    }
  } else {
    ElMessageBox.alert('积分不足，无法兑换', '提示', {type: 'warning'});
  }
};

onMounted(async () => {
  await getCoupons();
  await getUserPoints();
});
</script>

<style scoped>
.coupon-list {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  gap: 10px;
}

.coupon-item {
  width: calc(33.33% - 10px);
  margin-bottom: 15px;
}

.box-card {
  width: 100%;
}

.card-header {
  font-size: 18px;
  font-weight: bold;
}

.user-points {
  margin-top: 15px;
  font-size: 16px;
  font-weight: bold;
}
</style>